<?php

namespace app\store\model;

use app\store\model\Category as CategoryModel;
use think\Cache;
use app\common\model\Lesson as LessonModel;

/**
 * 课程模型
 * Class Category
 * @package app\store\model
 */
class Lesson extends LessonModel
{
    /**
     * 添加新记录
     * @param $data
     * @return false|int
     */
    public function add($data)
    {
        if (CategoryModel::isUseds($data['category_id'])){
            $data = $this->createdata($data);
            if($this->allowField(true)->save($data)){
                 CategoryModel::used($data['category_id']);
                return true;
            }else{
                return false;
            }
        }else{
            $this->error = "该章节已有内容";
            return false;
        }

    }

    /**
     * 编辑记录
     * @param $data
     * @return bool|int
     */
    public function edit($data)
    {
        if (isset($data['category_id'])){
            if ($data['category_id'] == $data['category_id_old']){
                //category 没有编号
                if ($this->allowField(true)->save($data)){
                    return true;
                }else{
                    return false;
                }
            }else{//有变化
                if (CategoryModel::isUseds($data['category_id'])){
                    if ($this->allowField(true)->save($data)){
                        //设置不可用
                        CategoryModel::used($data['category_id']);
                        //设置可用
                        CategoryModel::used($data['category_id_old'],0);
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    $this->error = "该章节已有内容";
                    return false;
                }
            }

        }else{
            return $this->allowField(true)->save($data) !== false;
        }


    }

    /**
     * 删除商品分类
     * @param $lesson_id
     * @return bool|int
     */
    public function remove($lesson_id)
    {
        $category_id = $this->category_id;
        return $this->transaction(function () use ($category_id,$lesson_id) {
            (new LessonDetails)->where('lesson_id','=',$lesson_id)->delete();
            // 更新对应课程章节状态
            CategoryModel::used($category_id,0);
            $status =  $this->delete();
            return $status;
        });
    }

    private function createdata($data){
        if (!isset($data['wxapp_id'])) {
            $data['wxapp_id'] = self::$wxapp_id;
        }
        return $data;
    }
}
